package com.example.email;


import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

/**
 * 邮件发送实现类
 * 
 * @author witon
 * @version $Id: EmailServiceImpl.java, v 0.1 2017年1月25日 上午10:31:36 witon Exp $
 */
@Service
public class EmailServiceImpl implements IEmailService {
    private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    //邮件发送
    @Autowired
    private JavaMailSender      mailSender;

    /**
     * 发送文本邮件
     * @see com.witontek.ehospital.service.base.IEmailService#sendMail(com.witontek.ehospital.domain.base.vo.SendEmailVo)
     */
    @Override
    public void sendMail(SendEmailVo emailVo) {
    	
    	//JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    	
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(emailVo.getFromEmail());
        message.setTo(emailVo.getToEmail().split(","));
        message.setSubject(emailVo.getSubject());
        message.setText(emailVo.getContent());
        mailSender.send(message);
    }

    /**
     * 发送富文本邮件
     * @see com.witontek.ehospital.service.base.IEmailService#sendMailHtml(com.witontek.ehospital.domain.base.vo.SendEmailVo)
     */
    @Override
    public void sendMailHtml(SendEmailVo emailVo) {
    	//JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(emailVo.getFromEmail());
            if(emailVo.getToEmail() != null && emailVo.getToEmail().indexOf(",") > 0){
                helper.setTo(emailVo.getToEmail().split(","));
            }else{
                helper.setTo(emailVo.getToEmail());
            }
            helper.setSubject(emailVo.getSubject());
            helper.setText(emailVo.getContent(), true);
            mailSender.send(message);
        } catch (MessagingException e) {
            logger.error("发送邮件异常", e);
        }
    }

}
